document.addEventListener('DOMContentLoaded', function() {
    // 属性升级按钮事件
    document.querySelectorAll('.upgrade-btn').forEach(btn => {
        btn.addEventListener('click', async function() {
            const stat = this.dataset.stat;
            const cost = parseInt(this.dataset.cost);
            
            try {
                const response = await fetch('/game/upgrade/stat/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: JSON.stringify({
                        stat: stat,
                        cost: cost
                    })
                });
                
                const data = await response.json();
                if (data.success) {
                    // 更新显示
                    updateStats(data.new_stats);
                    updateGold(data.new_gold);
                } else {
                    alert(data.message);
                }
            } catch (error) {
                console.error('升级失败:', error);
            }
        });
    });

    // 技能升级按钮事件
    document.querySelectorAll('.skill-upgrade-btn').forEach(btn => {
        btn.addEventListener('click', async function() {
            const skillId = this.dataset.skillId;
            
            try {
                const response = await fetch('/game/upgrade/skill/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: JSON.stringify({
                        skill_id: skillId
                    })
                });
                
                const data = await response.json();
                if (data.success) {
                    // 更新技能显示
                    updateSkillLevel(skillId, data.new_level);
                    updateGold(data.new_gold);
                } else {
                    alert(data.message);
                }
            } catch (error) {
                console.error('技能升级失败:', error);
            }
        });
    });
});

function updateStats(newStats) {
    Object.keys(newStats).forEach(stat => {
        const element = document.querySelector(`.stat-${stat} .current-value`);
        if (element) {
            element.textContent = newStats[stat];
        }
    });
}

function updateGold(newGold) {
    document.querySelector('.resource.gold span').textContent = newGold;
}

function updateSkillLevel(skillId, newLevel) {
    const skillCard = document.querySelector(`[data-skill-id="${skillId}"]`)
        .closest('.skill-card');
    skillCard.querySelector('.skill-level').textContent = `等级: ${newLevel}`;
} 